import json, asyncio, time, re

def remove_equal_sign(data):
    index = data.find('=')
    if index == -1:
        return data
    else:
        return data[index + 1:]


bk_pattern = re.compile(r'(?<=:").+?(?=")')
def format_bk_ranking(data):
    l = bk_pattern.findall(data)
    data = []
    for i in l:
        data.append(i.split(','))
    data = sorted(data, key = lambda bk : float(bk[5]), reverse = True)
    return data


sssjColumn = [
'', 'name', '', 'trade', 'preclose', 'open', 'vol', 'outvol', 'invol', 'buy1', 'buy1vol', 'buy2', 'buy2vol', 'buy3', 'buy3vol', 'buy4', 'buy4vol', 'buy5', 'buy5vol', 'sell1', 'sell1vol', 'sell2', 'sell2vol', 'sell3', 'sell3vol', 'sell4', 'sell4vol', 'sell5', 'sell5vol', '', '', 'change', 'changepercent', 'high', 'low', '', '', 'amount', 'turnover', 'ttm', '', '', '', 'amplitude', 'circulatingAmount', 'totalAmount', 'pb', 'zt', 'dt', 'qrr', '', 'average', 'pe', 'spe']
def format_sssj(data):
    result = {}
    indexColumn = []
    dataColumn = []
    stocks = data.split(';')
    for stock in stocks:
        if stock == '':
            continue
        tmp = stock.split('=')
        if not len(tmp) < 2:
            if len(tmp[1]) < 20:
                pass
            else:
                index = tmp[0].rfind('_') + 1
                symbol = tmp[0][index:]
                indexColumn.append(symbol)
                dataStr = tmp[1].strip()[1:-1]
                datas = dataStr.split('~')
                dataColumn.append(datas)

    result['columns'] = sssjColumn
    result['index'] = indexColumn
    result['data'] = dataColumn
    return result
    res = json.dumps(result)
    if res == '{}':
        return 'null'
    else:
        return res


def format_k(datas):
    items = datas.split('\\n\\\n')
    if items[1][0] == 'n':
        start = 2
    else:
        start = 1
    items = [x.split(' ') for x in items[start:-1]]
    index = [int(time.mktime(time.strptime(x[0], '%y%m%d'))) for x in items]
    datas = [x[1:] for x in items]
    d = {'index':index, 'data':datas}
    return d


def format_tick(datas):
    items = datas.split('\\n\\\n')
    date = items[1][-6:]
    items = [x.split(' ') for x in items[2:-1]]
    index = [int(time.mktime(time.strptime(date + x[0], '%y%m%d%H%M'))) for x in items]
    datas = [x[1:] for x in items]
    d = {'index':index, 'data':datas}
    return d


def get_jsonlist(text):
    res = re.search('''(?<='|")(.+)(?='|")''', text)
    if res:
        text =  res.groups()[0]
    text = text.replace('^', '"],["')
    text = text.replace('~', '","')
    res = '[["' + text + '"]]'
    return json.loads(res)


def create_symbol(code, sc):
    if sc == '51':
        return 'sz' + code
    elif sc == '1':
        return 'sh' + code
    else:
        return ''